package com.sofa.shark.file.config;

import com.sofa.shark.file.encode.HashMapEncoder;
import com.sofa.shark.file.remotefile.RemoteFileServerSevice;
import feign.Feign;
import feign.Request;
import feign.Retryer;
import feign.gson.GsonDecoder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author tonyp
 * @date 2020.4.3 文件服务相关配置
 */
@Configuration
@ConditionalOnProperty(name = "files.enabled", matchIfMissing = true)
public class RemoteFileAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public RemoteFileProperties remoteFileProperties() {
        return new RemoteFileProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    public RemoteFileServerSevice getRemoteFileService() {
        return Feign.builder()
                .encoder(new HashMapEncoder())
                .decoder(new GsonDecoder())
                .options(new Request.Options(remoteFileProperties().getConnectTimeoutMillis(),
                        remoteFileProperties().getReadTimeoutMillis()))
                .retryer(new Retryer.Default(remoteFileProperties().getPeriod(),
                        remoteFileProperties().getMaxPeriod(),remoteFileProperties().getMaxAttempts()))
                .target(RemoteFileServerSevice.class, remoteFileProperties().getFileUrl());
    }

}
